// 发送信息给background
var sendMessageToBackground = (action, data, callback) => {
    chrome.runtime.sendMessage({action: action, data: data}, callback)
};

function message (msg,type) {
    msg = msg || "采集到我们后台,请稍等...";
    console.log(msg)
    var html = '<div class="lihai-message ' + (type ? type : '') + '">' + msg + '<span class="remove-message">×</span></div>';
    var len = $('body').find('.lihai-message').length;
    if(len == 0){
        setToHtml(html);
    }else{
        $('body .lihai-message').remove();
        setToHtml(html)
    }
}
function setToHtml(html){
    $(html).appendTo('body').fadeIn(function () {
        var $el = $(this);
        $el.find('.remove-message').click(function(){
            $(this).closest('.lihai-message').remove();
        });
        setTimeout(function () {
            $el.fadeOut(function () {
                $el.remove();
            });
        }, 2000);//2s 后消失
    });
}

//文档加载函数
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
      }
    }
}
//封装xpath
function getElementByXpath(xpath, el) {
    el = el || document
    return document.evaluate(xpath, el, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
}
//睡眠
function sleep(time){
    return new Promise((resolve) => setTimeout(resolve, time));
}
//0-今天，1-明天，2-后天
function getDate(n) {
    const today = new Date();
    today.setDate(today.getDate() + n); // 日期加1，得到明天的日期

    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');

    const formattedDate = `${year}${month}${day}`;
    return formattedDate;
}
//爬取的天数数组
function getDateList() {
    let arr = []
    for (var i = 0; i < 8; i++) {
        arr.push(getDate(i))
    }
    return arr
}
//跳到下一个采集页继续采集
async function jumpCollectPage () {
    chrome.storage.local.get(['urls','date'],result => {
        if (result.urls && result.urls.length > 0) {
            let url = result.urls.shift()
            chrome.storage.local.set({
                urls: result.urls,
            });
            location.href = url
        } else {
            let dateList = getDateList()
            let key = 0
            for (var i = 0; i < dateList.length; i++) {
                if (result.date == dateList[i]) {
                    key = (i + 1) % dateList.length
                    break
                }
            }
            location.href = "https://www.aiscore.com/"+dateList[key]
        }
    });
}